// tasks 数据结构
let tasks = [
    { id: 1, text: "睡觉", completed: false },
    { id: 2, text: "吃饭", completed: true },
    { id: 3, text: "打豆豆", completed: false }
]
console.log(tasks);


// 添加按钮增加点击事件，获取按钮
let addbtn = document.querySelector('.addtask .addbtn')
let inputText = document.querySelector('.addtask input')
let ul = document.querySelector('.tasklist ul')
let allBtn = document.querySelector("#allbtn")
let completedBtn = document.querySelector("#completed")
let uncompletedBtn = document.querySelector("#uncompleted")

//事件添加
window.addEventListener('load', function () {
    renderTasks(tasks);
})

addbtn.addEventListener('click', function () {
    //数据添加
    //1.产生数据-task对象
    //数组最后一个值+1
    let id = tasks[tasks.length - 1].id + 1;
    text = inputText.value;
    const task = {
        id: id, text: inputText.value, completed: false
    };
    //2.把对象放到tasks数组中
    tasks.push(task);
    renderTasks(tasks)
    console.log(tasks);
    //3.渲染

})

//三个按钮
allBtn.addEventListener('click',function() {
    renderTasks(tasks);

})
completedBtn.addEventListener('click',function() {
    renderTasks(tasks.filter(task=>task.completed));
})
uncompletedBtn.addEventListener('click',function() {
    renderTasks(tasks);
})

function renderTasks(tasks) {
    //清空现有的ul中的html
    console.log(ul);

    ul.innerHTML = '';
    tasks.forEach(task => {
        // 创建一个元素
        const li = document.createElement('li');
        // 修改元素的html内容
        li.innerHTML = `
            <div class="left">
              <input type="checkbox" checked=${task.completed ? 'checked' : ''}>
              <span class="${task.completed ? 'line' : ''}">${task.text}</span>
            </div>
            <div class="btn-group">
                <button>编辑</button>
                <button>删除</button>
            </div>
        `;

        //   const input = li.querySelector("input");
        //   input.checked = task.completed;
        //   console.log(task.completed);

        // 把元素放到ul中
        ul.appendChild(li)
        //底部统计数据的渲染
        //生成统计数据
        let all = tasks.length;
        let completed = tasks.filter(task => { task.completed }).length;
        let uncompleted = all - completed;

        //修改对应函数的数据
        // document.querySelectorAll('.footer span');
        // sapns[0].textContent = `全部${all}`;
        // sapns[1].textContent = `已完成${completed}`;
        // sapns[2].textContent = `未完成${uncompleted}`;

        //获取元素的另外方法
        document.querySelector('.footer span:nth-child(1)').textContent = `全部 ${all}`;
        document.querySelector('.footer span:nth-child(2)').textContent = `已完成 ${completed}`;
        document.querySelector('.footer span:nth-child(3)').textContent = `未完成 ${uncompleted}`;


    });
}


